package com.itheima.service.impl.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.DishDao;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.exception.NoDataException;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Component
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishDao dishDao;
    @Override
    public DishDto fillDish(DishDto dishDto) {

        String categoryId = dishDto.getCategoryId();
        Category cag = categoryDao.selectById(categoryId);
        //填充字段
        dishDto.setType(cag.getType());
        dishDto.setSort(cag.getSort());
        dishDto.setCategoryName(cag.getName());

//        //将口味表存入数据库
//        dishFlavorService.save(dishFlavor);
        this.save(dishDto);
        String dishId = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return dishDto;
    }

    @Override
    public DishDto getdishDto(String id) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getId,id);
        Dish dish = this.getOne(queryWrapper);
        if(dish==null){
            throw new NoDataException();
        }
        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper1);

        //将查找到的数据封装到dto里.
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        BeanUtils.copyProperties(flavors,dishDto.getFlavors());

        return dishDto;
    }

    @Override
    public boolean update(DishDto dishDto) {

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getName,dishDto.getName());
        Dish dish = this.getOne(queryWrapper);
        if(dish==null){
            log.info("待改数据不存在" );
            throw new NoDataException();
        }
        //删除菜品
        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
           //先删除口味表
        queryWrapper1.eq(DishFlavor::getDishId,dish.getId());
        dishFlavorService.remove(queryWrapper1);
     //  将传入的dto赋值给dish 此方法不行由于默认值null也会覆盖
//        Dish dish1 = new Dish();
//        BeanUtils.copyProperties(dishDto,dish1);
        this.remove(queryWrapper);
        String categoryId = dishDto.getCategoryId();
        Category cag = categoryDao.selectById(categoryId);
        //填充字段
        dishDto.setType(cag.getType());
        dishDto.setSort(cag.getSort());
        dishDto.setCategoryName(cag.getName());
        save(dishDto);
        //新建一个新的dto 与传入的dto 完全一致,再调用独有的方法更新数据 ,最后修改id值
        //todo 需要参考其他人代码寻找优化代码 这就是陀shit
//        DishDto dishDto1 = new DishDto();
//        BeanUtils.copyProperties(dishDto,dishDto1);
//        dishDto1.setId(dish.getId());
//        //更新除id以外的其他数据
//        this.updateById(dishDto1);
//        //更新id;
//        LambdaQueryWrapper<Dish> queryWrapper2 = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Dish::getName,dishDto.getName());
//        Dish dish2 = this.getOne(queryWrapper2);
//        dish2.setId(dishDto.getId());
//        this.remove(queryWrapper);
//        this.save(dish2);
        //添加当前提交过来的口味数据---
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId((dishDto.getId()));
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

        return true;


    }

    @Override
    public boolean delete(String ids) {
        //切割传进来的id 并遍历删除
        String[] strings = ids.split(",");
        for (int i = 0; i < strings.length; i++) {
//            String id =strings[i];
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId,strings[i]);
            Dish dish = this.getOne(queryWrapper);
            if(dish==null){
                log.info("要删除的数据不存在");
                throw new NoDataException();
            }
            //同时删除口味表相关字段
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,strings[i]);
            dishFlavorService.remove(queryWrapper1);
            this.remove(queryWrapper);
        }
        return true;
    }

    @Override
    public boolean updateState(String ids) {
        //切割并修改
        String[] strings = ids.split(",");
        for (int i = 0; i < strings.length; i++) {
//            String id =strings[i];
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId,strings[i]);
            Dish dish = this.getOne(queryWrapper);
            //修改state字段设置
            String status = dish.getStatus();
            if(status.equals("0")){
                dish.setId("1");
            }else if (status.equals("1")){
                dish.setId("0");
            }else {
                log.info("非法字段 未知数据异常");
                throw  new NoDataException();
            }
        }
        return true;
    }

    @Override
    public List<DishDto> selectPage(Integer page, Integer pageSize , String name) {
        Page page1 = new Page<>(page,pageSize);
        QueryWrapper wrapper = new QueryWrapper();
      //判断字段是否带有name值
        if(StringUtils.hasText(name)){
            wrapper.eq("name",name);
        }
        page1=dishDao.selectPage(page1,wrapper);
        //取出查询的集合列表
        List<Dish> dishList = page1.getRecords();
        List<DishDto> dishDtos = new ArrayList<>();

//        Set<String> categoryIds =new HashSet<>();

        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //复制对象
            BeanUtils.copyProperties(dish,dishDto);
            dishDtos.add(dishDto);
            //由于建表原因,如果需要修改字段,则需引入下面这段,从id再获取到名字,最后再存入
            //口味表,这里就不添加,如果有需要再回来做修改
//            String categoryId = dishDto.getCategoryId();
//            categoryIds.add(categoryId);
        }
       page1.setRecords(dishDtos);
       return  dishDtos;
    }

}
